<template>
    <div class="chat-msg" ref="chat_msg">
        <transition-group name="van-slide-up">
            <div class="box"
                v-for="(item, index) in messages"
                :key="index"  
                :style="{ justifyContent: is_user(item) ? 'flex-end' : '' }"
            >
                <!-- 如果是对方发的就显示对方的头像  -->
                <van-image  round fit="cover" width="3.125rem" height="3.125rem" 
                    :src="item.sender_headImg" 
                    :class="{ paiyipai: ifPaiyipai }"
                    v-if="!is_user(item)"
                    @click="handleSingleClick(item)"
                />
                <span
                    v-html="setMessageHtml(item.content)"
                    :style="{ 
                        backgroundColor: is_user(item) ? 'rgb(1, 153, 254)' : 'rgb(255, 255, 255)', 
                        color: is_user(item) ? 'rgb(255, 255, 255)' : 'rgb(0, 0, 0)'
                    }"
                />
                <!-- 如果是我发的信息就显示我的头像 -->
                <van-image round fit="cover" width="3.125rem" height="3.125rem" 
                    :src="user.headImgUrl"
                    v-if="is_user(item)" 
                />
            </div>
        </transition-group>
    </div>
</template>

<script>
    import { mapState } from "vuex";

    export default {
        data() {
            return {
                flag: true,
                time: "",
                ifPaiyipai: false,
            };
        },
        computed: {
            ...mapState(["user", 'groupChatList', "friendList"]),
            messages() {         // 聊天信息
                let tmp = [];

                if ('user_id' in this.$route.query) {
                    tmp = this.friendList.find(item => item.friendId._id == this.$route.query.user_id).messages;
                } else if ('groupChat_id' in this.$route.query) {
                    tmp = this.groupChatList.find(item => item._id == this.$route.query.groupChat_id).messages;
                }

                if (tmp == undefined)
                    return [];
                else
                    return tmp;
            },
            vanSlide() {        // 来判断动画是从左边来还是右边来
                if ('user_id' in this.$route.query) {
                    return "van-slide-right";
                } else if ('groupChat_id' in this.$route.query) {
                    return "van-slide-left";
                } else {
                    return '';
                }

                // if (this.friendList[this.active]?.ChatInformationIndex !== undefined) 
                // {
                //     if (this.ChatInformation[this.friendList[this.active].ChatInformationIndex].at(-1).my)
                //         return "van-slide-right";
                //     else 
                //         return "van-slide-left";
                // }
                // else {
                //     return "";
                // }
            },
            element() {         // 计算属性返回该元素
                return this.$refs.chat_msg;
            },
        },
        methods: {
            paiyipai(event) {
                console.log(event);
            },
            handleSingleClick(value) {           // 点击按钮为跳转个人页面，双击为抖一抖
                if (this.flag) {
                    this.flag = false;

                    this.time = setTimeout(() => {
                        this.flag = true;
                        this.$router.push({ path: "/home", query: { user_id: value.sender } });
                    }, 500);
                } else {
                    this.flag = true;
                    this.ifPaiyipai = true;

                    setTimeout(() => this.ifPaiyipai = false, 500);
                    clearTimeout(this.time);
                }
            },
            setMessageHtml(content) {
                return content.replace(
                    /\[(\d+\.gif)\]/g, 
                    '<img src="./gif/$1" width="25" height="25" style="vertical-align: middle;">'
                );
            },
            is_user(value) {
                if (value.sender == this.user._id)
                    return true;
                else
                    return false;
            },
        },
        watch: {
            $route: {                           // 监测 route 来判断当前处于的页面
                handler(to, from) {
                    if (to.name == "chat") {
                        // 处于聊天页面的时候, 滚动条top的距离，等于他自己的高度，一有消息就滑到顶部
                        this.$nextTick(() =>  this.element.scrollTop = this.element.scrollHeight); 
                    }

                    if (to.name != "chat") {
                        // 退出聊天页面的时候, 清除滚动条动画
                        this.element.style.scrollBehavior = "";
                    }
                },
                immediate: true,
            },
            'messages.length'(to, from) {       // 监测信息的长度以此来给它加滚动条动画
                if (to > from ?? 0) {
                    this.$nextTick(() => {
                        this.element.style.scrollBehavior = "smooth";    // 设置滚动动画
                        this.element.style.overflowY = "auto";           // 因为之前隐藏了y轴滚动条，这是让他显示出来
                        this.element.scrollTop = this.element.scrollHeight;
                    });
                }
            },
        },
        mounted() {
            // 页面加载完成后，设置滚动条行为，一进来就滑到底
            this.$nextTick(() => {
                this.element.style.overflowY = "auto";           // 显示y轴滚动条
                this.element.scrollTop = this.element.scrollHeight;   // 滚动条top的距离，等于他自己的高度
            });
        },
    };
</script>

<style lang="less" scoped>
    @keyframes shake {
        0% {
            transform: translateX(0);
        }
        25% {
            transform: translateX(-5px);
        }
        50% {
            transform: translateX(5px);
        }
        75% {
            transform: translateX(-5px);
        }
        100% {
            transform: translateX(0);
        }
    }
    // 拍一拍动画
    .paiyipai {
        animation: shake 0.5s infinite;
    }
    .chat-msg {
        overflow: auto;
        overflow-y: hidden;
        overflow-x: hidden;
        .box {
            width: 100%;
            display: flex;
            align-items: flex-start;
            margin: 0.625rem 0px;
            position: relative;
            .van-image {
                margin: 0px 0.625rem;
            }
            span {
                display: inline-block;
                align-self: flex-end;
                max-width: 16.25rem;
                background-color: rgb(255, 255, 255);
                font-weight: 600;
                font-family: "仿宋";
                border-radius: 0.625rem;
                padding: 0.625rem;
                white-space: pre-wrap;
                height: max-content;
                letter-spacing: 0.0938rem;
                word-wrap: break-word; 
                word-break: break-all; 
            }
        }
    }
</style>